package com.lanou.wuyou.gift.home;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.lanou.wuyou.gift.R;
import com.lanou.wuyou.gift.base.BaseFragment;
import com.lanou.wuyou.gift.bean.HomeBean;
import com.lanou.wuyou.gift.tools.NetResultInterface;
import com.lanou.wuyou.gift.tools.NetWorkInstance;

/**
 * Created by dllo on 17/3/14.
 */

public class HomeListFragment extends BaseFragment{

    private ListView listView;
    private HomeBean homeBean;

    //系统默认调用构造方法,所以无法重写构造方法的方式传值
    //官方推荐方法:
    public static HomeListFragment newInstance(String url){

        Bundle args = new Bundle();
        args.putString("url",url);
        HomeListFragment fragment = new HomeListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int setLayout() {
        return R.layout.fragment_home_list;
    }

    @Override
    public void initView(View view) {
        listView = (ListView) view.findViewById(R.id.home_list_list_view);
    }

    @Override
    public void initData() {

        final HomeListAdapter adapter = new HomeListAdapter(context);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int mId = homeBean.getData().getItems().get(position).getId();
                Intent intent = new Intent(getActivity(),HomeListItemWebOne.class);
                intent.putExtra("id",mId);
                Log.d("HomeListFragment", "mId:" + mId);
                startActivity(intent);
            }
        });

        //获取参数(网址)
        String urlStr = getArguments().getString("url");

        //网络请求
        NetWorkInstance.getInstance().netRequest(urlStr, new NetResultInterface() {
            @Override
            //当网络请求成功时
            public void success(String str) {

                //Gson使用步骤
                //1.添加Gson包
                //2.下载插件GsonFormat
                //3.创建数据类GsonFormat

                //gson解析
                Gson gson = new Gson();
                //解析后的数据存于homeBean中
                homeBean = gson.fromJson(str,HomeBean.class);
                adapter.setHomeBean(homeBean);
            }

            @Override
            //当网络请求失败时
            public void fail(String str) {

            }
        });
    }
}
